package micro.beauty.common.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
* @Description:    线程池配置
* @Author:         Liuliya
* @CreateDate:     2020/10/9 21:25
*/
@EnableAsync
@Configuration
public class ThreadPoolConfig implements AsyncConfigurer {
    private final Logger log = LoggerFactory.getLogger(ThreadPoolConfig.class);
    private final static String THREAD_NAME_PREFIX = "MICRO-BEAUTY-";
    private final static int THREAD_QUEUE_SIZE = 50;
    private final static int AWAIT_TERMINATION_SECONDS = 60;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        int cpu = Runtime.getRuntime().availableProcessors();
        log.info("当前设备服务器CPU核数为:{}", cpu);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(cpu);
        executor.setMaxPoolSize(cpu);
        executor.setQueueCapacity(THREAD_QUEUE_SIZE);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(AWAIT_TERMINATION_SECONDS);
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }


    @Override
    public Executor getAsyncExecutor() {
        return threadPoolTaskExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> {
            StringBuilder sb = new StringBuilder();
            for (Object param : objects) {
                sb.append(param).append(",");
            }
            log.error("异常信息->{}, 方法->{}, 参数->{}",
                    throwable.getMessage(), method.getName(), sb.toString());
        };
    }
}
